<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='form'
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='checkAndPushSubmitConfig'
      >
        <a-divider orientation="left">基础设置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="Model:" name="spMode">
              <a-select v-model:value="form.spMode">
                <a-select-option :value="0">Disable speed alarm</a-select-option>
                <a-select-option :value="1">Enable when current speed in the range</a-select-option>
                <a-select-option :value="2">Enable when current speed outside the range</a-select-option>
                <a-select-option :value="3">Enable when current speed within or outside the range</a-select-option>
                <a-select-option :value="4">Enable when current speed changed from inside to outside the range</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Min Speed(km/h):' name='minSpeed'>
              <a-input-number :min="0" :max="400" v-model:value='form.minSpeed' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Max Speed(km/h):' name='maxSpeed'>
              <a-input-number :min="0" :max="400" v-model:value='form.maxSpeed' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Validity(秒):' name='validity'>
              <a-input-number :min="0" :max="3600" v-model:value='form.validity' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='发送周期(秒):' name='sendInterval'>
              <a-input-number :min="30" :max="3600" v-model:value='form.sendInterval' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='2' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
            <a-button type='primary' html-type='submit' :loading='formSubmitLoading'>
              提交
            </a-button>
            <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='readGTSPD' :loading='readLoading'>
              读取
            </a-button>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='6' :sm='24' :xs='24'></a-col>
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {
  VehicleConfigSpeedAlarmApi
} from "@/api/property/vechile/VehicleConfigSpeedAlarmApi";

export default {
  name: 'DeviceVehicleConfigSpeedAlarm',
  components: {

  },
  props: {
    data: Object
  },
  async created() {
    this.getDetail();
  },
  data() {
    return {
      form : {},
      currentConfig : {},
      loading : false,

      formSubmitLoading : false,
      formSubmitTimer : undefined,

      readLoading : false,
      readTimer : undefined
    };
  },
  methods: {
    getDetail() {
      let that = this;
      VehicleConfigSpeedAlarmApi.detail({"recordId" : this.data.recordId}).then(result => {
        that.form = result || {};
        that.currentConfig = JSON.parse(JSON.stringify(result || {}));
      });
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail2(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //-------提交
    clearSubmitConfig(){
      this.formSubmitLoading = false;
      clearInterval(this.formSubmitTimer);
    },

    checkSubmitConfig(){
      let that = this;
      this.checkProcess(4, this.clearSubmitConfig, function(){
        that.getDetail();
      });
    },

    checkAndPushSubmitConfig() {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 4
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitConfigSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitConfigSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({ old: this.currentConfig, update: this.form}),
        dictate : 4, //AT+GTSPD=
        sceneDictate : 4 //SpeedAlarm
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.formSubmitLoading = true; //转圈
          this.formSubmitTimer = setInterval(this.checkSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //----读取
    clearReadSubmitConfig(){
      this.readLoading = false;
      clearInterval(this.readTimer);
    },

    checkReadSubmitConfig(){
      let that = this;
      this.checkProcess(603, this.clearReadSubmitConfig, function(){
        that.getDetail();
      });
    },

    readGTSPD() {
      let workerDetailParams = {
        recordId: this.data.recordId,
        sceneDictate: 603
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailParams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitReadSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitReadSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({}),
        dictate : 603, //读取GTSPD
        sceneDictate : 603
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.readLoading = true; //转圈
          this.readTimer = setInterval(this.checkReadSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
